from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.hashers import make_password
from django.db import models
from django.contrib.auth.models import User,AbstractBaseUser,PermissionsMixin,UserManager,BaseUserManager
from shortuuidfield import ShortUUIDField

#员工状态信息的选择
class UserStatusChoices(models.IntegerChoices):
    ACTIVED = 1  #已经激活
    LOCKED = 3  #锁定
    UNACTIVE = 2 #未激活

#重写usermanager函数
class OAUserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, realname, email, password, **extra_fields): #密码这个字段来源于AbstractBaseUser
        """
        创建用户
        """
        if not realname:
            raise ValueError('必须设置真实姓名')
        email = self.normalize_email(email)
        user = self.model(realname=realname, email=email, **extra_fields) #相当于OAUser
        user.password = make_password(password)
        user.save(using=self._db)
        return user

    #创建普通用户
    def create_user(self, realname, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(realname, email, password, **extra_fields)

    #创建超级用户
    def create_superuser(self, realname, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('status',UserStatusChoices.ACTIVED) #创建的超级用户默认激活状态


        if extra_fields.get('is_staff') is not True:
            raise ValueError('超级用户必须设置 is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('超级用户必须设置 is_superuser=True.')

        return self._create_user(realname, email, password, **extra_fields)

#重写user模型
class OAUser(AbstractBaseUser, PermissionsMixin):
    """
    自定义的user模型
    """
    uid = ShortUUIDField(primary_key=True)
    realname = models.CharField(
        max_length=150,
        unique=False, #不唯一，保证允许同名
    )
    email = models.EmailField(unique=True,blank=False) #邮箱唯一且不能为空
    telephone = models.CharField(max_length=11,blank=False)
    is_staff = models.BooleanField(default=True,)
    status = models.IntegerField(
        choices=UserStatusChoices.choices,
        default=UserStatusChoices.UNACTIVE
    )
    #只需关注status，无需关注is_active(django自带)
    is_active = models.BooleanField(default=True,)
    date_joined = models.DateTimeField(auto_now_add=True)

    department = models.ForeignKey('OADepartment',null=True,
                                   on_delete=models.SET_NULL,
                                   related_name='staffs',
                                   related_query_name='staffs')

    objects = OAUserManager() #执行上面定义的函数功能，用来实现创建用户功能

    EMAIL_FIELD = 'email'
    '''
    USERNAME_FIELD是用来鉴权的,会把authenticate的参数传给USERNAME_FIELD指定的字段
    from django.contrib.auth import authenticate
    authenticate(request, username='xxxxx@qq.com')
    django默认将username作为验证名，不符合需求，所以改为email
    '''
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['realname','password'] #指定必传字段，但不能包含EMAIL_FIELD和USERNAME_FIELD设置过的值

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        return self.realname

    def get_short_name(self):
        return self.realname

    # class Meta:
    #     ordering = ("-date_joined")

#部门模型
class OADepartment(models.Model):
    name = models.CharField(max_length=100)
    intro = models.TextField(max_length=200)
    leader = models.OneToOneField(OAUser,null=True,
                                  on_delete=models.SET_NULL,
                                  related_name = 'leader_department',
                                  related_query_name='leader_department')
    manage = models.ForeignKey(OAUser,null=True,
                                  on_delete=models.SET_NULL,
                                  related_name = 'leader_departments',
                                  related_query_name='leader_departments')

